package com.draemoncode.socket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JFrame;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.draemoncode.event.IEvent;
import com.draemoncode.event.QiangzhuangEvent;
import com.draemoncode.event.XiazhuEvent;
import com.draemoncode.ui.SimpleApplication;
import com.draemoncode.util.JSONUtil;

public class DefaultMinaIoHandlerAdapter extends IoHandlerAdapter {

	private SimpleApplication view;
	
	private List<IEvent> events = new ArrayList<>();
	
	private IoSession session;

	public IoSession getSession() {
		return session;
	}

	public void setSession(IoSession session) {
		this.session = session;
	}

	public DefaultMinaIoHandlerAdapter(JFrame view) {
		super();
		this.view = (SimpleApplication) view;
		events.add(new QiangzhuangEvent());
		events.add(new XiazhuEvent());
	}

	/**
	 * 连接创建事件
	 */
	@Override
	public void sessionCreated(IoSession session) {
		// 显示客户端的ip和端口
		System.out.println(session.getRemoteAddress().toString());
		if(this.session == null){
			this.session = session;
			view.setSession(session);
		}
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

	@Override
	public void sessionOpened(IoSession iosession) throws Exception {
		System.out.println("会话打开");
		super.sessionOpened(iosession);
	}

	/**
	 * 消息接收事件
	 */
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String strMsg = message.toString();
		HashMap args = JSONUtil.parse(strMsg, HashMap.class);
		System.out.println("收到客户端消息成功received: " + JSONUtil.toJson(args));
		for (IEvent iEvent : events) {
			if(iEvent.shoudProcess(args)){
				iEvent.busiAction(session, view, args);
				iEvent.viewAction(session, view, args);
			}
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		System.out.println("发送服务器端消息成功send: " + message);
		super.messageSent(session, message);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		// System.out.println("IDLE" + session.getIdleCount(status));
	}
}
